package filter;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import util.RSAUtils;

@WebFilter({ "/JspFilter", "*.jsp" })
public class JspFilter implements Filter {

	public JspFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String url = req.getRequestURI();
		if (!url.endsWith("login.jsp")) {
			User user = (User) req.getSession().getAttribute("user");
			if (user == null) {
				res.sendRedirect("login.jsp");
				return;
			}
		} else {
			HashMap<String, Object> map;
			try {
				map = RSAUtils.getKeys();
				// 生成公钥和私钥
				RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
				RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
				req.getSession().setAttribute("privateKey", privateKey);// 私钥保存在session中，用于解密
				// 公钥信息保存在页面，用于加密
				String publicKeyExponent = publicKey.getPublicExponent().toString(16);
				String publicKeyModulus = publicKey.getModulus().toString(16);
				request.setAttribute("publicKeyExponent", publicKeyExponent);
				request.setAttribute("publicKeyModulus", publicKeyModulus);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
